package com.ws.gold.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ws.gold.domain.RealtimeGoldPrice;
import com.ws.gold.mapper.RealtimeGoldPriceMapper;
import com.ws.gold.service.RealtimeGoldPriceService;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ws
 * @create 2025/6/23
 */
@Service
@AllArgsConstructor
public class RealtimeGoldPriceServiceImpl extends ServiceImpl<RealtimeGoldPriceMapper, RealtimeGoldPrice> implements RealtimeGoldPriceService {

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public RealtimeGoldPrice getLatestGoldPrice() {

        RealtimeGoldPrice realtimeGoldPrice = new RealtimeGoldPrice();
        try {
            String response = HttpRequest.get("https://www.huilvbiao.com/api/gold_indexApi")
                    .timeout(5000) // 设置5秒超时
                    .execute()
                    .body();

            if (StrUtil.isNotBlank(response)) {
                String priceStr = StrUtil.subBetween(response, "var hq_str_gds_AUTD=\"", ",");
                if (priceStr != null) {
                    realtimeGoldPrice.setPrice(Double.parseDouble(priceStr));
                }
            }else {
                throw new RuntimeException("获取金价失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        save(realtimeGoldPrice);
        // 缓存数据
        JSONObject dataFromRedis = getChartDataFromRedis();
        if(ObjUtil.isNotEmpty(dataFromRedis)){
            JSONArray xLabels = dataFromRedis.getJSONArray("xLabels");
            JSONArray yValues = dataFromRedis.getJSONArray("yValues");
            xLabels.add(LocalDateTimeUtil.formatNormal(realtimeGoldPrice.getCreateTime()));
            yValues.add(realtimeGoldPrice.getPrice());
            redisTemplate.opsForValue().set("chartData", dataFromRedis, 1, TimeUnit.DAYS);
        }

        return realtimeGoldPrice;
    }

    @Override
    public JSONObject getChartData() {
        JSONObject dataFromRedis = getChartDataFromRedis();
        if (ObjUtil.isEmpty(dataFromRedis)) {
            List<RealtimeGoldPrice> list = lambdaQuery().between(RealtimeGoldPrice::getCreateTime, LocalDateTimeUtil.offset(LocalDateTime.now(), -24, ChronoUnit.HOURS), LocalDateTime.now()).orderByAsc(RealtimeGoldPrice::getCreateTime).list();
            dataFromRedis = JSONObject.of("xLabels", list.stream().map(item -> LocalDateTimeUtil.formatNormal(item.getCreateTime())).collect(Collectors.toList()), "yValues", list.stream().map(RealtimeGoldPrice::getPrice).collect(Collectors.toList()));
            redisTemplate.opsForValue().set("chartData", dataFromRedis,1, TimeUnit.DAYS);
        }
        return dataFromRedis;
    }

    /**
     * 从redis中获取缓存
     */
    private JSONObject getChartDataFromRedis() {
        Object o = redisTemplate.opsForValue().get("chartData");
        if (ObjUtil.isEmpty(o)) {
            return null;
        }
        return JSONObject.parseObject(JSON.toJSONString(o));
    }

}
